import { requestClient } from '#/api/request';

/**
 * 上传分片参数
 */
export interface UploadChunkParams {
  /** 文件对象 */
  file: File;
  /** 文件唯一标识符 */
  identifier: string;
  /** 当前分片编号 */
  chunkNumber: number;
  /** 总分片数 */
  totalChunks: number;
  /** 分片大小 */
  chunkSize: number;
}

/**
 * 上传分片结果
 */
export interface UploadChunkResult {
  /** 是否成功 */
  success: boolean;
  /** 错误信息 */
  message?: string;
  /** 是否已合并所有分片 */
  merged?: boolean;
  /** 合并后的文件路径 */
  filePath?: string;
}

/**
 * 确认上传结果
 */
export interface ConfirmUploadResult {
  /** 是否成功 */
  success: boolean;
  /** 错误信息 */
  message?: string;
  /** 文件路径 */
  filePath?: string;
}

const API_BASE_URL = '/upload';

/**
 * 上传文件分片
 * @param params 分片参数
 */
export async function uploadChunk(params: UploadChunkParams): Promise<UploadChunkResult> {
  const { file, identifier, chunkNumber, totalChunks, chunkSize } = params;
  
  const start = (chunkNumber - 1) * chunkSize;
  const end = Math.min(start + chunkSize, file.size);
  const chunk = file.slice(start, end);
  
  const formData = new FormData();
  formData.append('file', chunk, file.name);
  
  return requestClient.post<UploadChunkResult>(`${API_BASE_URL}/chunk`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
    params: {
      identifier,
      chunkNumber: chunkNumber.toString(),
      totalChunks: totalChunks.toString(),
      chunkSize: chunkSize.toString(),
      totalSize: file.size.toString(),
      filename: file.name,
    },
  });
}

/**
 * 检查分片状态
 * @param identifier 文件标识符
 * @param chunkNumber 分片编号
 */
export async function checkChunkStatus(identifier: string, chunkNumber: number): Promise<boolean> {
  return requestClient.get<boolean>(`${API_BASE_URL}/chunk/status`, {
    params: {
      identifier,
      chunkNumber,
    },
  });
}

/**
 * 确认上传并移动文件
 * @param filename 文件名
 * @param targetDirectory 目标目录（可选）
 */
export async function confirmUpload(filename: string, targetDirectory?: string): Promise<ConfirmUploadResult> {
  const params: Record<string, string> = { filename };
  if (targetDirectory) {
    params.targetDirectory = targetDirectory;
  }
  
  return requestClient.post<ConfirmUploadResult>(`${API_BASE_URL}/confirm`, null, {
    params,
  });
}

/**
 * 获取已上传文件列表
 */
export async function getFileList(): Promise<string[]> {
  return requestClient.get<string[]>(`${API_BASE_URL}/files`);
}